package com.wei.czz.framework.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.tool.PageDto;
import com.wei.czz.common.utils.CopyUtils;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.common.fileFlow.FileFlowFormVo;
import com.wei.czz.framework.common.service.SnowflakeService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wei.czz.framework.common.dao.FileFlowDao;
import com.wei.czz.framework.common.entity.FileFlowEntity;
import com.wei.czz.framework.common.service.FileFlowService;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wei
 * date: 2025-03-23 12:39:15
 * className: FileFlowServiceImpl
 * version: 1.0
 * description:
 */
@Service("fileFlowService")
@AllArgsConstructor
public class FileFlowServiceImpl extends ServiceImpl<FileFlowDao, FileFlowEntity> implements FileFlowService {

    private static final Logger log = LoggerFactory.getLogger(FileFlowServiceImpl.class);

    private final SnowflakeService snowflakeService;

    @Override
    public void saveOrEdit(FileFlowEntity fileFlow) {
        // 获取操作用户
        Long userId = SecurityUtils.getOrDefaultUserId(CommonEnum.ZERO.getLongValue());
        String username = SecurityUtils.getOrDefaultUsername(StringUtils.EMPTY);
        Date date = new Date();

        if (Objects.isNull(fileFlow.getId())) {
            // 新增
            fileFlow.setFileNo(snowflakeService.get())
                    .setDeleteStatus(CommonEnum.ZERO.getValue())
                    .setUpdateTime(date)
                    .setUpdateUser(StringUtils.EMPTY)
                    .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                    .setCreateTime(date)
                    .setCreateUser(username)
                    .setCreateUserId(userId);

            int count = baseMapper.insert(fileFlow);
            log.info("新增文件上传记录完成。count={}", count);
        } else {
            // 编辑
            fileFlow.setUpdateTime(date)
                   .setUpdateUser(username)
                   .setUpdateUserId(userId);

            int count = baseMapper.updateById(fileFlow);
            log.info("编辑文件上传记录完成。count={}", count);
        }
    }

    @Override
    public Long copy(Long id, String originalFileName) {

        /*
            获取文件上传记录
         */
        FileFlowEntity fileFlow = baseMapper.selectById(id);
        if (Objects.isNull(fileFlow)) {
            log.info("文件上传记录不存在。id={}", id);
            throw new CzzException();
        }

        // 复制对象
        FileFlowEntity copyFileFlow = CopyUtils.map(fileFlow, FileFlowEntity.class);
        copyFileFlow.setId(null)
                .setOriginalFileName(originalFileName);

        /*
            保存
         */
        this.saveOrEdit(copyFileFlow);

        return copyFileFlow.getFileNo();
    }

    @Override
    public FileFlowEntity find(Long fileNo) {

        LambdaQueryWrapper<FileFlowEntity> fileFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 条件匹配
        fileFlowLambdaQueryWrapper.eq(FileFlowEntity::getFileNo, fileNo)
                .eq(FileFlowEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 匹配一条
        fileFlowLambdaQueryWrapper.last("limit 1");
        // 查询
        List<FileFlowEntity> fileFlowList = baseMapper.selectList(fileFlowLambdaQueryWrapper);
        log.info("文件编号查询文件上传记录完成。list.size={}", fileFlowList.size());
        if (fileFlowList.isEmpty()) {
            return null;
        }
        return fileFlowList.get(0);
    }

    @Override
    public FileFlowEntity find(String fileHash) {
        LambdaQueryWrapper<FileFlowEntity> fileFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 条件匹配
        fileFlowLambdaQueryWrapper.eq(FileFlowEntity::getFileHash, fileHash)
                .eq(FileFlowEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 匹配一条
        fileFlowLambdaQueryWrapper.last("limit 1");
        // 查询
        List<FileFlowEntity> fileFlowList = baseMapper.selectList(fileFlowLambdaQueryWrapper);
        log.info("文件哈希值查询文件上传记录完成。list.size={}", fileFlowList.size());
        if (fileFlowList.isEmpty()) {
            return null;
        }
        return fileFlowList.get(0);
    }

    @Override
    public List<FileFlowEntity> findList(List<Long> fileNoList, List<String> fileHashList) {
        if (CollectionUtils.isEmpty(fileNoList) && CollectionUtils.isEmpty(fileHashList)) {
            log.info("获取文件上传记录，文件编号列表和文件哈希值列表均为空。");
            return Collections.emptyList();
        }

        LambdaQueryWrapper<FileFlowEntity> fileFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 条件匹配
        fileFlowLambdaQueryWrapper.in(!CollectionUtils.isEmpty(fileNoList), FileFlowEntity::getFileNo, fileNoList)
                .in(!CollectionUtils.isEmpty(fileHashList), FileFlowEntity::getFileHash, fileHashList)
               .eq(FileFlowEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<FileFlowEntity> fileFlowList = baseMapper.selectList(fileFlowLambdaQueryWrapper);
        log.info("批量查询文件上传记录完成。list.size={}", fileFlowList.size());

        return fileFlowList;
    }

    @Override
    public PageDto<FileFlowEntity> getFileFlowPageList(FileFlowFormVo formVo) {

        // mp分页对象
        Page<FileFlowEntity> page = new Page<>(formVo.getPage(), formVo.getLimit());

        // 条件匹配
        LambdaQueryWrapper<FileFlowEntity> fileFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        fileFlowLambdaQueryWrapper.eq(Objects.nonNull(formVo.getFileNo()), FileFlowEntity::getFileNo, formVo.getFileNo())
                .eq(StringUtils.isNotBlank(formVo.getFileHash()), FileFlowEntity::getFileHash, formVo.getFileHash())
                .eq(FileFlowEntity::getDeleteStatus, formVo.getDeleteStatus());
        // 排序
        fileFlowLambdaQueryWrapper.orderByDesc(FileFlowEntity::getUpdateTime);
        // 分页查询
        baseMapper.selectPage(page, fileFlowLambdaQueryWrapper);
        log.info("分页查询文件上传记录完成。totalNum={} list.size={}", page.getTotal(), page.getRecords().size());

        return new PageDto<>(page);
    }
}